package com.store.satring.web;
import com.store.satring.dos.GeneralLedger;
import com.store.satring.dos.GeneralLedgerDetail;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/generalledgerdetails")
@Controller
public class GeneralLedgerDetailController {

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid GeneralLedgerDetail generalLedgerDetail, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		int generalLedgerId = generalLedgerDetail.getGeneralLedgerId();
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, generalLedgerDetail);
            return "generalledgerdetails/create";
        }
        uiModel.asMap().clear();
        generalLedgerDetail.persist();
        
        GeneralLedger generalLedger = GeneralLedger.findGeneralLedger(Long.parseLong(generalLedgerId+""));
        generalLedger.getGeneralLedgerDetails().add(generalLedgerDetail);
        double amount = getGLDetailAmount(generalLedger);
        generalLedger.setTotalPaymentReceived(amount + generalLedger.getAdvanceAmount());
        generalLedger.setBalanceAmount(generalLedger.getInvoiceAmount() - generalLedger.getTotalPaymentReceived());
        generalLedger.persist();
        
        return "redirect:/generalledgers/" + generalLedgerId+"?form";
    }

	private double getGLDetailAmount(GeneralLedger generalLedger) {
		//Update related amounts
        List<GeneralLedgerDetail> generalLedgerDetails = generalLedger.getGeneralLedgerDetails();
        double amount = 0;
        for (GeneralLedgerDetail glDetail : generalLedgerDetails) {
        	amount += glDetail.getAmount();
		}
		return amount;
	}

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel, HttpServletRequest httpServletRequest) {
		String generalLedgerId = httpServletRequest.getParameter("generalLedger");
		GeneralLedgerDetail generalLedgerDetail = new GeneralLedgerDetail();
		generalLedgerDetail.setGeneralLedgerId(Integer.parseInt(generalLedgerId));
		generalLedgerDetail.setReceivedOn(new Date());
        populateEditForm(uiModel, generalLedgerDetail);
        
        return "generalledgerdetails/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("generalledgerdetail", GeneralLedgerDetail.findGeneralLedgerDetail(id));
        uiModel.addAttribute("itemId", id);
        return "generalledgerdetails/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("generalledgerdetails", GeneralLedgerDetail.findGeneralLedgerDetailEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) GeneralLedgerDetail.countGeneralLedgerDetails() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("generalledgerdetails", GeneralLedgerDetail.findAllGeneralLedgerDetails(sortFieldName, sortOrder));
        }
        addDateTimeFormatPatterns(uiModel);
        return "generalledgerdetails/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid GeneralLedgerDetail generalLedgerDetail, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		String generalLedgerId = httpServletRequest.getParameter("generalLedgerId");
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, generalLedgerDetail);
            return "generalledgerdetails/update";
        }
        uiModel.asMap().clear();
        generalLedgerDetail.merge();
        
        GeneralLedger generalLedger = GeneralLedger.findGeneralLedger(Long.parseLong(generalLedgerId));
        double amount = getGLDetailAmount(generalLedger);
        generalLedger.setTotalPaymentReceived(amount + generalLedger.getAdvanceAmount());
        generalLedger.setBalanceAmount(generalLedger.getInvoiceAmount() - generalLedger.getTotalPaymentReceived());
        generalLedger.merge();

        return "redirect:/generalledgers/" + generalLedgerId + "?form";
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel, HttpServletRequest httpServletRequest) {
		String generalLedgerId = httpServletRequest.getParameter("generalLedger");
		GeneralLedgerDetail generalLedgerDetail = GeneralLedgerDetail.findGeneralLedgerDetail(id);
		generalLedgerDetail.setGeneralLedgerId(Integer.parseInt(generalLedgerId));
        populateEditForm(uiModel, generalLedgerDetail);
        return "generalledgerdetails/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        GeneralLedgerDetail generalLedgerDetail = GeneralLedgerDetail.findGeneralLedgerDetail(id);
        generalLedgerDetail.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/generalledgerdetails";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("generalLedgerDetail_receivedon_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, GeneralLedgerDetail generalLedgerDetail) {
        uiModel.addAttribute("generalLedgerDetail", generalLedgerDetail);
        addDateTimeFormatPatterns(uiModel);
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
